<?php

namespace App\Recharge\Logic;

use App\Traits\Create;
use App\Models\Mysql\XnOrder;
use App\Models\Admin\Supplier;
use App\Models\Mysql\XnTerraceInfo;
use App\Models\Mysql\XnSupplierGoods;
use App\Recharge\Bean\BasicInformation;
use Illuminate\Database\Eloquent\Builder;
use App\Recharge\Bean\SupplierApiConfigBean;
use App\Models\Admin\InterfaceConfiguration;
use App\Models\Admin\SupplierInterfacePermissions;
use App\Recharge\Exceptions\SuspensionOfEnforcement;

class ConfigLogic extends BaseLogic
{
    /**
     * 供应商自定义配置
     *
     * @param int $goods_belong
     * @return string
     */
    public function supplierApiConfig(int $goods_belong): string
    {
        return XnTerraceInfo::s($this->supplier)->where('sid', $goods_belong)->value('datas') ?? '';
    }

    /**
     * 查询供应商接口是否启用记录
     *
     * @param int $interface_id 接口id
     * @return Builder|SupplierInterfacePermissions|null
     */
    public function supplierApiEnable(int $interface_id): Builder|SupplierInterfacePermissions|null
    {
        return SupplierInterfacePermissions::query()->where('sid', $this->supplier->id)->where('interface_id', $interface_id)->first();
    }

    /**
     * 获取供应商接口域名
     *
     * @return string 域名
     * @throws SuspensionOfEnforcement
     */
    public function supplierHost(): string
    {
        $config = $this->supplier->config;
        if (!$config) {
            throw new SuspensionOfEnforcement('未找到供应商配置');
        }
        if (!$config->domain) {
            throw new SuspensionOfEnforcement('未配置供应商域名');
        }
        return sprintf("%s://%s", $config->domain_ssl == 1 ? 'https' : 'http' ,$config->domain);
    }

    /**
     * 供应商自定义接口配置检测
     *
     * @param InterfaceConfiguration $api 第三方接口
     * @return SupplierApiConfigBean
     * @throws SuspensionOfEnforcement
     */
    public function supplierApiConfigCheck(InterfaceConfiguration $api): SupplierApiConfigBean
    {
        $config = json2array($this->supplierApiConfig($api->id));
        if (!$config) {
            throw new SuspensionOfEnforcement(sprintf("请先配置%s接口配置", $api->title));
        }
        $bean = new SupplierApiConfigBean();
        // 检测appid_title
        if ($api->appid_title) {
            if ((!isset($config[$api->appid_title]) || !$config[$api->appid_title])) {
                throw new SuspensionOfEnforcement(sprintf("未配置%s", $api->appid_title));
            }
            $bean->setAppid($config[$api->appid_title]);
        }
        // 检测secret_key
        if ($api->private_key_title) {
            if (!isset($config[$api->private_key_title]) || !$config[$api->private_key_title]) {
                throw new SuspensionOfEnforcement(sprintf("未配置%s", $api->private_key_title));
            }
            $bean->setSecretKey($config[$api->private_key_title]);
        }
        return $bean;
    }

    /**
     * @param InterfaceConfiguration $api 第三方接口
     * @param XnOrder $order 订单
     * @param XnSupplierGoods|array $parent 主商品
     * @param SupplierApiConfigBean|null $config 供应商自定义配置
     * @param array $child 子商品
     * @return BasicInformation
     * @throws SuspensionOfEnforcement
     */
    public function makeBasicInformation(InterfaceConfiguration $api, XnOrder $order, XnSupplierGoods|array $parent, ?SupplierApiConfigBean $config = null, array $child = []): BasicInformation
    {
        if (!is_array($parent)) {
            $parent = $parent->toArray();
        }
        if (empty($child)) {
            $child = $parent;
        }
        $basic = new BasicInformation();
        if (!$config) {
            $config = $this->supplierApiConfigCheck($api);
        }
        $basic->setSupplierNum($config->getAppid());
        $basic->setSecretKey($config->getSecretKey());
        // 回调地址
        $basic->setNotifyUrl(sprintf('%s/apis/notify/%s', $this->supplierHost(), $api->en));

        $basic->setOrderNo($order->order_sn);
        $basic->setGoodsId($child['goods_code']);
        $basic->setRechargeNum($order->goods_num);
        $basic->setStartCharging($parent['start_charging']);
        $basic->setAccount($order->account);
        $basic->setUnitPrice($child['unit_price']);
        $basic->setIp($order->ip ?? '');
        $basic->setFaceValue($child['faceValue'] ?? 0);
        $basic->setAccountType($child['account_type'] ?? '');
        $basic->setGoodsName($order->goods_name);
        $basic->setGameAreaId('');
        $basic->setGameAreaName('');
        $basic->setGameServerId('');
        $basic->setGameServerName('');
        $basic->setProductId($child['productId'] ?? '');
        $basic->setProductType($child['productType'] ?? 0);
        $basic->setGameAcct('');
        $basic->setGameType($child['game_type'] ?? '');
        $basic->setDashangAccountType($child['dashang_account_type'] ?? 0);
        $basic->setCateId($child['cate_id'] ?? 0);
        $basic->setOperatorCode($child['operator_code'] ?? 0);

        return $basic;
    }

    /**
     * 获取第三方接口配置
     *
     * @param int $goods_belong 第三方归属id
     * @return InterfaceConfiguration
     * @throws SuspensionOfEnforcement
     */
    public function getApiConfig(int $goods_belong): InterfaceConfiguration
    {
        $api = InterfaceConfiguration::findFromCache($goods_belong, ttl: 3600);
        if (!$api) {
            throw new SuspensionOfEnforcement('未找到第三方配置信息');
        }
        // 判断是否需要权限
        if ($api->permission_required == 2) {
            return $api;
        }
        $enable = $this->supplierApiEnable($api->id);
        if (!$enable) {
            throw new SuspensionOfEnforcement('未启用当前第三方');
        }
        return $api;
    }
}
